<?php

namespace app\admin\controller\shop\setting;

use app\admin\controller\shop\Setting;
use app\shop\library\ShopHelper;
use ba\Filesystem;
use think\helper\Arr;

class Basic extends Setting
{
    public function initialize(): void
    {
        parent::initialize();

        $this->model = new \app\admin\model\shop\Setting();
    }

    protected string $configGroupKey = 'basic_group';

    protected function beforeSave(array $data): array
    {
        if (Arr::get($data, 'auto_cancel_time')) {
            if ($data['auto_cancel_time'] < 1 || $data['auto_cancel_time'] > 48) {
                $this->error('自动取消时间范围为1-48小时');
            }
        }
        if (Arr::get($data, 'auto_receive_time')) {
            if ($data['auto_cancel_time'] < 1) {
                $this->error('自动收货时间需大于1天');
            }
        }
        if (Arr::get($data, 'auto_evaluate_time')) {
            if ($data['auto_evaluate_time'] < 1) {
                $this->error('自动评价时间需大于1天');
            }
        }
        if (Arr::get($data, 'apply_refund_time')) {
            if ($data['apply_refund_time'] < 1) {
                $this->error('自动收货时间需大于1天');
            }
        }
        if (Arr::get($data, 'apply_refund_time')) {
            if ($data['apply_refund_time'] < 1) {
                $this->error('申请售后时间需大于1天');
            }
        }
        if (Arr::get($data, 'api_url')) {
            $apiUrl = rtrim($data['api_url'], '/');
            if (!filter_var($apiUrl, FILTER_VALIDATE_URL)) {
                $this->error('Api请求域名格式错误');
            }
            if (str_ends_with($apiUrl, 'index.php')) {
                $this->error('Api请求地址不能以 index.php 结尾');
            }
            $data['api_url'] = rtrim($data['api_url'], '/');
        }
        if (Arr::get($data, 'api_name')) {
            $backendEntrance = ShopHelper::get_setting('api_name', 'shop');
            if ($backendEntrance != $data['api_name']) {
                $this->setApiNameMapping($data['api_name']);
            }
        }

        return $data;
    }

    /**
     * 设置Api应用名称映射
     * @param string $apiName
     * @return void
     */
    private function setApiNameMapping(string $apiName): void
    {
        $configPath     = 'config/app.php';
        $defaultApiName = 'shop';
        // 设置应用映射
        if (!preg_match("/^\/[a-zA-Z0-9]+$/", $apiName)) {
            $this->error(__('API应用名称请以 / 开头，且只包含数字和字母'));
        }
        // 设置应用别名映射
        $appMap      = config('app.app_map');
        $adminMapKey = array_search($defaultApiName, $appMap);
        if ($adminMapKey !== false) {
            unset($appMap[$adminMapKey]);
        }
        $newBackendEntrance = ltrim($apiName, '/');
        if ($newBackendEntrance != $defaultApiName) {
            $appMap[$newBackendEntrance] = $defaultApiName;
        }
        $appConfigFilePath = Filesystem::fsFit(root_path() . 'config/app.php');
        $appConfigContent  = @file_get_contents($appConfigFilePath);
        if (!$appConfigContent) $this->error(__('配置文件写入失败: %s', [$configPath]));

        $appMapStr = '';
        foreach ($appMap as $newAppName => $oldAppName) {
            $appMapStr .= "'$newAppName' => '$oldAppName', ";
        }
        $appMapStr = rtrim($appMapStr, ', ');
        $appMapStr = "[$appMapStr]";

        $appConfigContent = preg_replace("/'app_map'(\s+)=>(\s+)(.*)\/\/ 域名/s", "'app_map'\$1=>\$2$appMapStr,\n    // 域名", $appConfigContent);
        $result           = @file_put_contents($appConfigFilePath, $appConfigContent);
        if (!$result) $this->error(__('配置文件写入失败: %s', [$configPath]));
    }

    protected function afterSave(array $data): void
    {
        $miniappPushUrl = ShopHelper::full_api_url('/wechatMessagePush/miniapp');

        $this->model->where('name', 'miniapp_push_url')->update(['value' => $miniappPushUrl]);
    }
}